/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.storage.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.enfry.storage.BaseService;
import com.enfry.storage.api.IBaseStorageFile;
import com.enfry.storage.api.IClient;
import com.enfry.storage.api.IFileOperate;
import com.enfry.storage.common.Constants;
import com.enfry.storage.entity.Client;
import com.enfry.storage.exception.ExCode;
import com.enfry.storage.exception.StorageException;
import com.jweb.framework.core.Context;

/**
 * 上传service
 * @Title com.enfry.storage.service.FileUploadService
 * @author liulei
 * @date 2016年7月25日
 */
public class FileUploadService extends BaseService {

	@Resource
    private IFileOperate fileOperate;
    @Resource
    private IClient client;
    @Resource
    private IBaseStorageFile iBaseStorageFile;
    
    public void upload(Context ctx) {
        // 获取文件信息：后缀名、大小等
        CommonsMultipartFile multipart = ctx.getData(Constants.FILE_PARAM_NAME);
        String filename = multipart.getOriginalFilename();
        String fileExtName = filename.substring(filename.lastIndexOf(".") + 1);
        long fileSize = multipart.getSize();
        logger.debug("===========================================================================");
        logger.debug("上传文件临时目录：" + multipart.getStorageDescription());
        logger.debug("上传文件属性名：" + multipart.getName());
        logger.debug("上传文件大小：" + fileSize/1024 + "KB");
        logger.debug("上传文件名：" + filename);
        logger.debug("===========================================================================");
        
        try {
            // 参数前缀
            String encrypt = ctx.getData("encrypt");
            String prefix = encrypt == null ? "1" : encrypt;

            // 保存文件
            byte[] fileBytes = "0".equals(encrypt) ? multipart.getBytes() : (byte[]) ctx.getData(Constants.FILE_ENCRYPT_PARAM_NAME);
            String fileCode = fileOperate.upload(fileBytes, prefix+"."+fileExtName);
            
            // 获取客户端密钥
            String appKey = ctx.getData("appKey");
            Client c = client.getByAppKey(appKey);
            String appSecret = c.getSecret();
            
            // 获取文件URL
            //String serverUrl = ((HttpServletRequest)ctx.getChannelContext().getRequest()).getRequestURL().toString();
            String serverUrl = ctx.getData("serverUrl");
            serverUrl = serverUrl.substring(0, serverUrl.lastIndexOf("/"));
            String fileUrl = fileOperate.getIMGUrl(serverUrl, fileCode, appKey, appSecret);
            
            Map<String, Object> data = new HashMap<>();
            data.put("fileCode", fileCode);
            data.put("fileUrl", fileUrl);
            
            iBaseStorageFile.insertBaseStorageFile(fileCode, fileUrl);
            
            this.ajaxData(ctx, data);
        } catch (StorageException e) {
            this.ajaxError(ctx, e);
        } catch (Exception e) {
            this.ajaxError(ctx, ExCode.RUNTIME);
        }
    }
}
